package cc.telecomdigital.tdstock.activity.groups.index;

import java.util.List;
import java.util.Map;
import java.util.Vector;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.DefaultClickHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.StringUtils;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Http.Services.H_HttpServiceRequest.H_UserClient_HttpRequest_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.BMPBaseActivity;
import cc.telecomdigital.tdstock.activity.groups.IndexGroup;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.MonitorUtil;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.SaveBookMarkAsyncTask;
import cc.telecomdigital.tdstock.adapter.IndexCopHolder;
import cc.telecomdigital.tdstock.model.IndexFuturesInfo;
import cc.telecomdigital.tdstock.utils.Futures;

/**
 * Index COP
 * 
 * @author ouyangzhihui
 */
public class BMPIndexCOPListActivity extends BMPBaseActivity
{
	static final private String	TAG	= "BMPIndexCOPListActivity";

	private ListView			_listView;
	private IndexCopItemAdapter	_adapter;
	private List<IndexCopHolder>	_list;
	private Button				_toolBtnReturn;
	private TextView			_top_bar_title;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cop_index);

		Button _btn_update_data = (Button) findViewById(R.id._btn_update_data);
		_btn_update_data.setVisibility(View.VISIBLE);
		_btn_update_data.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG, "BMP update data");

				loadDataUpdateUI(false);
			}
		});

		_top_bar_title = (TextView) findViewById(R.id.top_bar_title);
		_toolBtnReturn = (Button) findViewById(R.id.more_returnbtn);
		_toolBtnReturn.setFocusable(true);
		_toolBtnReturn.setClickable(true);
		_toolBtnReturn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				TDStockLog.d(TAG,
						"close current activity and forwarding to the previous");

				Intent intent = new Intent(getApplicationContext(),
						IndexOptionsListActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				SwitchForwardActivity(IndexOptionsListActivity.class,
						intent);
			}
		});

		_listView = (ListView) findViewById(R.id.index_cop_list);
		_list = new Vector<IndexCopHolder>();
		int index = 0;
		for (String item : Futures.TypeName)
		{
			IndexCopHolder holder = new IndexCopHolder();
			holder.left = new TextView(this);
			holder.mid = new TextView(this);
			holder.id = index++;
			holder.itemCode = item;
			_list.add(holder);
		}
		_adapter = new IndexCopItemAdapter(LayoutInflater.from(this), _list);
		_listView.setAdapter(_adapter);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		upateTitle();
		loadDataUpdateUI(true);
	}

	private void upateTitle()
	{
		String titleContext = ((ITDLApplication) getApplicationContext())
				.getString(CommonDefn.TOP_BAR_TITLE);
		if (((ITDLApplication) getApplicationContext()).getDataMode() == CommonDefn.DataMode.Delay)
		{
			_top_bar_title.setText("COP("
					+ getResources().getString(
							R.string.delay_mode_title_tips) + ")");
		}
		else
		{
			_top_bar_title.setText(titleContext);
		}
		_top_bar_title.postInvalidate();

		((ITDLApplication) getApplicationContext()).putString(
				CommonDefn.TOP_BAR_TITLE, "");
	}

	public void OnUpdateCOP(final int itemPos, final Futures update)
	{
		for (IndexCopHolder holder : _list)
		{
			if (holder.itemCode.equals(update.getName()))
			{
				String tempCOP = update.getCop();
				// TDStockLog.d(TAG,
				// "isCop="+update.getIsCop()+" , cop="+update.getCop()+" , last="+update.getLast());
				// if(!"Y".equals(update.getIsCop()))
				// {
				// tempCOP = update.getLast();
				// }

				if (tempCOP == null || tempCOP.equals(""))
				{
					tempCOP = CommonDefn.DEFAULT_FIELD_VALUE2;
				}

				String formattedCOP = StringUtils.formatToDp(tempCOP, 0);
				holder.mid.setText(formattedCOP);

				switch (itemPos)
				{
					case 0:
					case 1:
						holder.left.setText(String.format("恆生指數 %s月期貨",
								update.getMm()));
						break;
					default:
						holder.left.setText(String.format("國企指數 %s月期貨",
								update.getMm()));
						break;
				}
			}
		}
		_listView.invalidateViews();
	}

	private String[]	futuresCopNames	= { "恆%月C", "恆%月C", "國%月C", "國%月C" };

	public class AddItemClickHandler extends DefaultClickHandler
	{
		private String	_item;
		private String	_adapter;
		private String	_fieldName;
		private String	_fieldValue;
		private String	_fieldNet;
		private String	_fieldNetPercentage;

		public AddItemClickHandler(Context context, int pos)
		{
			super(context);
			setItemPos(pos);
		}

		public void setItemPos(int pos)
		{
			_item = Futures.TypeName[pos];
			_adapter = IndexFuturesInfo.ADAPTER + IndexFuturesInfo.COP;
			setFields(futuresCopNames[pos], "", "", "");
		}

		public void setFields(String name, String value, String net,
				String netpercentage)
		{
			_fieldName = name;
			_fieldValue = value;
			_fieldNet = net;
			_fieldNetPercentage = netpercentage;
		}

		@Override
		protected void onDefaultAction()
		{
/*			DBHelper dbHelper = new DBHelper(BMPIndexCOPListActivity.this);
			try
			{*/
				/*
				 * int customerId = 1;
				 * if(((ITDLApplication)getApplicationContext
				 * ()).getModeType()==CommonDefn.ModeType.DELARY){ if
				 * (dbHelper.isSubscribeItemExist(customerId, _item, _adapter))
				 * { new CustomizeDialog(getMyOwnContext(), "",
				 * getResources().getString
				 * (R.string.monitor_exist_index)).show(); } else if
				 * (dbHelper.isFullWithItemInMonitor(customerId)) { new
				 * CustomizeDialog(getMyOwnContext(), "",
				 * getResources().getString
				 * (R.string.monitor_is_full_with_items)).show(); } else { long
				 * result = dbHelper.insertSubscribeItem(customerId, _item,
				 * _adapter, _fieldName, _fieldValue, _fieldNet,
				 * _fieldNetPercentage); if (result > 0) { modify by
				 * zor(ouyangzhihui) String temp = _item.length() >= 2 ?
				 * _item.substring(0, 2) : _item; startAnimat(temp); }
				 * 
				 * TDStockLog.d(TAG, "insert result:" + result); } } //mode is
				 * not delay else{
				 */
				/*
				 * if(MonitorUtil.getInstance().addBookMarkItem(_item,
				 * CommonDefn
				 * .BookMarkType.cop.getBookMarkType(),BMPIndexCOPListActivity
				 * .this)){ _messageHandler.post(new SaveMonitor(_item.length()
				 * >= 2 ? _item.substring(0, 2) :
				 * _item,MonitorUtil.items,BMPIndexCOPListActivity.this)); //} }
				 */
				
/*			}
			catch (Exception e)
			{
				e.printStackTrace();
				TDStockLog.d(
						TAG,
						"insert result:" + e.getMessage() == null ? "unknown exception!"
								: e.getMessage());
			}
			finally
			{
				dbHelper.cleanup();
			}*/
			
			new SaveBookMarkAsyncTask(_item,
					CommonDefn.BookMarkType.cop.getBookMarkType(),
					BMPIndexCOPListActivity.this,
					MonitorUtil.getInstance(),
					_item.length() >= 2 ? _item.substring(0, 2) : _item)
					.execute();
			
		}
	}

	// private class IndexCOPAsyncTask extends BaseAsyncTask
	// {
	// private Map<String, Futures> futuresList;
	// private boolean isBool = true;
	//
	// public IndexCOPAsyncTask(Context context)
	// {
	// super(context);
	// }
	//
	// public IndexCOPAsyncTask(Context context, boolean isBool)
	// {
	// super(context);
	// this.isBool = isBool;
	// }
	//
	// @Override
	// protected void onPreExecute()
	// {
	// if(isBool)
	// super.onPreExecute();
	// }
	//
	// @Override
	// protected Void doInBackground(String... params)
	// {
	// try
	// {
	// futuresList =
	// HttpDataBaseUtils.getDataByFutures_Cop(/*!((ITDLApplication)
	// getApplicationContext()).getIsRealtimeFutures()*/false,
	// ((ITDLApplication) getApplicationContext())
	// .getSessionAccount(), ((ITDLApplication)
	// getApplicationContext()).getSessionToken());
	//
	// }
	// catch (Exception e)
	// {
	// e.printStackTrace();
	// }
	//
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(Void result)
	// {
	// if(isBool)
	// super.onPostExecute(result);
	//
	// final Runnable myUpdateResults = new Runnable()
	// {
	// public void run()
	// {
	// for(int i = 0; i < futuresList.size(); i++)
	// {
	// OnUpdateCOP(i, futuresList.get(Futures.TypeName[i]));
	// }
	// }
	// };
	//
	// new Thread()
	// {
	// public void run()
	// {
	// if (_messageHandler != null)
	// _messageHandler.post(myUpdateResults);
	// }
	// }.start();
	// }
	// }

	// modify by zor(ouyangzhihui)
	public class IndexCopItemAdapter extends BaseAdapter
	{
		private LayoutInflater		minflater;
		private List<IndexCopHolder>	list;

		public IndexCopItemAdapter(LayoutInflater inflater,
				List<IndexCopHolder> list)
		{
			super();
			this.minflater = inflater;
			this.list = list;
		}

		@Override
		public int getCount()
		{
			return this.list.size();
		}

		@Override
		public Object getItem(int position)
		{
			return position < this.list.size() ? this.list.get(position)
					: null;
		}

		@Override
		public long getItemId(int position)
		{
			return position < this.list.size() ? this.list.get(position).id
					: -1l;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			IndexCopHolder commHolder = null;
			if (convertView == null)
			{
				convertView = minflater.inflate(R.layout.index_cop_item,
						null);
				commHolder = new IndexCopHolder();
				commHolder.left = (TextView) convertView
						.findViewById(R.id.cop_item_left);
				commHolder.mid = (TextView) convertView
						.findViewById(R.id.cop_item_mid);
				commHolder.right = (ImageView) convertView
						.findViewById(R.id.cop_item_right);

				commHolder.mid.setGravity(Gravity.RIGHT);
				// synchronize with iphone
				commHolder.left.setTextColor(Color.BLUE);
				commHolder.mid.setTextColor(Color.BLACK);
				convertView.setDrawingCacheBackgroundColor(Color.WHITE);

				convertView.setTag(commHolder);
			}
			else
			{
				commHolder = (IndexCopHolder) convertView.getTag();
			}
			commHolder.right.setOnClickListener(new AddItemClickHandler(
					BMPIndexCOPListActivity.this, position));

			if (this.list.get(position) != null
					&& this.list.get(position).left != null
					&& this.list.get(position).left.getText() != null)
				commHolder.left.setText(this.list.get(position).left
						.getText());
			if (this.list.get(position) != null
					&& this.list.get(position).mid != null
					&& this.list.get(position).mid.getText() != null)
				commHolder.mid.setText(this.list.get(position).mid
						.getText());

			return convertView;
		}
	}

	@Override
	protected void onPause()
	{
		super.onPause();
		TDStockLog.d(TAG, TAG + " onPause");
	}

	@Override
	protected void onStart()
	{
		super.onStart();
		TDStockLog.d(TAG, TAG + " onStart");
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();
		TDStockLog.d(TAG, TAG + " onRestart");
	}

	@Override
	protected void onStop()
	{
		super.onStop();
		TDStockLog.d(TAG, TAG + " onStop");
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		TDStockLog.d(TAG, TAG + " onDestroy");
	}

	@Override
	public void onBackPressed()
	{
		super.onBackPressed();
		TDStockLog.d(TAG, TAG + " onBackPressed");
	}

	@Override
	public ActivityGroupController GetActivityGroupController()
	{
		return IndexGroup.GetActivityGroupHostControl();
	}

	private void loadDataUpdateUI(boolean isBool)
	{
		// new IndexCOPAsyncTask(getMyOwnContext(), isBool).execute();

		if (isBool)
			SetShowProgressView(true);
		else
			SetShowProgressView(false);

		SendHttpRequest();
	}

	@Override
	protected H_CODE GetDataFromHttpServer()
	{
		return HttpAppInfo.SendBMPFuturesCOPRequest(actContext, this);
	}

	@Override
	protected void H_UserClient_HttpRequest_Response_Sub(
			H_UserClient_HttpRequest_Result iResult)
	{
		if (!iResult.MStatus.equals("0"))
		{
			ShowMessageDialog(iResult.MError + "(" + iResult.MStatus + ")");
			return;
		}
		updateData((Map<String, Futures>) iResult.objMapStores);
	}

	private void updateData(final Map<String, Futures> futuresList)
	{
		final Runnable myUpdateResults = new Runnable()
		{
			public void run()
			{
				for (int i = 0; i < futuresList.size(); i++)
				{
					OnUpdateCOP(i, futuresList.get(Futures.TypeName[i]));
				}
			}
		};

		new Thread()
		{
			public void run()
			{
				_messageHandler.post(myUpdateResults);
			}
		}.start();
	}
}
